from datetime import datetime,timedelta

def saveToRDEMARB(roads,road_emissions,save_dat,params):
    data = ""
    data += "RDEMARB.DAT     1.0             Initial configuration\n"
    data += "  1\n"
    data += "road source\n"
    data += "UTM\n"
    data += "  50N\n"
    data += "WGS-84  02-21-2003\n"
    data += "  KM\n"
    data += "UTC+0800\n"
    scope_start = changeDate(params[1],"before")
    scope_end = changeDate(params[2],"after",True)
    data += f"{scope_start}  {scope_end}\n"
    link_num = len(roads)
    data += f"   {link_num}    7\n"
    data += f"'SO2'    'SO4'    'NOX'    'HNO3'    'NO3'    'PM10'    'PM2.5'\n"
    data += f"  64    96    46    63    62    200    200\n"
    for road in roads:
        road_name = road
        road_emissions[road_name]
        road_code = road_emissions[road_name]["road_code"]
        links = roads[road_name]
        link_num = len(links)
        data += f"'{road_code}'              {link_num}\n"
        i = 1
        for link in links:
            x = link['x']
            y = link['y']
            z = link['elevation']
            data += f"    {i}.      {x}    {y}    {z}    0.000    0.000    0.000    0.000\n"
            i+=1
    time_points = create_time_points(params[1],params[2])
    for point in time_points:
        start_point = changeDate(point,"mid")
        end_point = changeDate(point,"mid",True)
        data += f"   {start_point}    {end_point}\n"
        ######
        for road in roads:
            road_name = road
            road_emissions[road_name]
            road_code = road_emissions[road_name]["road_code"]
            emissions = road_emissions[road_name]['emissions'][point]
            nox = emissions['nox']
            pm25 = emissions['pm25']
            data += f"'{road_code}'          2.0   4.2   3.5     0   0   {nox}   0   0   0   {pm25}\n"

    with open(save_dat, 'w', encoding='utf-8') as file:
        file.write(data)
    print(f"排放文件已保存到 {save_dat}")
    # 2024  280  00  0000  2024  290 23  3600
    return True

def saveToPTEMARB(roads,road_emissions,save_dat,params):
    data = ""
    data += "PTEMARB.DAT     2.1             Comments, times with seconds, time zone, coord info\n"
    data += "  1\n"
    data += "point-source\n"
    data += "UTM\n"
    data += "  50N\n"
    data += "WGS-84  02-21-2003\n"
    data += "  KM\n"
    data += "UTC+0800\n"
    scope_start = changeDate(params[1],"before")
    scope_end = changeDate(params[2],"after",True)
    data += f"{scope_start}  {scope_end}\n"
    link_num = len(roads)
    data += f"   {link_num}    7\n"
    data += f"'SO2'    'SO4'    'NOX'    'HNO3'    'NO3'    'PM10'    'PM2.5'\n"
    data += f"  64    96    46    63    62    200    200\n"

    for road in roads:
        road_name = road
        road_emissions[road_name]
        road_info = road_emissions[road_name]
        # print(road_info)
        x = road_info['x']
        y = road_info['y']
        road_code = road_info['road_code']
        z = road_info['elevation']
        # X-Coordinate,Y-Coordinate
        # Stack Height(m) 烟囱源高,Stack Diameter(m) 烟囱出口直径,Stack Base elevation(m) 烟囱海拔高
        # Building downwash flag(0=no,1=yes) 是否考虑建筑物下洗
        # Vertical Momentum flux flag(0.0 or 1.0) to simulate structures like rain hats 是否考虑垂直动量通量的影响
        # User defined flag
        # 'a5e11aa705849af9'            514.811  4058.033  18.0  2.0  124.0 0.00 1.0 0.00
        data += f"'{road_code}'            {x}    {y}    18.0    2.0    {z}    0.00    1.0    0.00\n"
    time_points = create_time_points(params[1],params[2])
    # Exit Temperature(deg. K) 烟囱出口烟气温度，单位 开尔文（Kelvin）
    # Exit Velocity(m/s)    烟囱出口流速
    # Initial sigma-y(m) for source 代表在水平侧向（垂直于平均风向的方向）上,单位 m
    # Initial sigma-z(m) for source 代表在垂直方向（垂直于地面的方向）上，单位米 m
    # Emission Rates(g/s) for each species   排放速率
    # 'a5e11aa705849af9'            323.15  150.0  0.0  0.0  0 0 0.308517 0  0 0 0.018035
    for point in time_points:
        start_point = changeDate(point,"mid")
        end_point = changeDate(point,"mid",True)
        data += f"   {start_point}    {end_point}\n"
        ######
        for road in roads:
            road_name = road
            road_emissions[road_name]
            road_code = road_emissions[road_name]["road_code"]
            emissions = road_emissions[road_name]['emissions'][point]
            nox = emissions['nox']
            pm25 = emissions['pm25']
            data += f"'{road_code}'            390   150.0   0.0   0.0   0   0   {nox}   0   0   0   {pm25}\n"

    with open(save_dat, 'w', encoding='utf-8') as file:
        file.write(data)
    print(f"排放文件已保存到 {save_dat}")
    # 2024  280  00  0000  2024  290 23  3600
    return True

def changeDate(date_str,scoap="",end_flag=False):
    date_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
    if scoap == "before":
        date_obj = date_obj - timedelta(days=1)
    elif scoap == "after":
        date_obj = date_obj + timedelta(days=1)
    # 提取年份
    year = date_obj.year
    # 计算一年中的第几天
    day_of_year = date_obj.timetuple().tm_yday
    # 提取小时
    hour = date_obj.hour
    second = "0000"
    if end_flag:
        second = "3600"
    return f"{year:04d} {day_of_year:03d} {hour:02d} {second}"


def create_time_points(start,end):
    start_date = datetime.strptime(start, "%Y-%m-%d %H:%M:%S")
    end_date = datetime.strptime(end, "%Y-%m-%d %H:%M:%S")
    time_points = []
    current_date = start_date
    while current_date <= end_date:
        time_points.append(current_date.strftime("%Y-%m-%d %H:%M:%S"))
        current_date += timedelta(hours=1)
    return time_points